package cn.huangsm.advance.lambda;

import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.DoubleSupplier;

/**
 * lambda表达式基本使用
 *
 * @author huang
 * @PACKAGE_NAME cn.huangsm.advance.lambda
 * @PROJECT_NAME advance-code
 * @date 2019/1/10
 */
@Slf4j
public class LambdaTest {

    public static void basicTest() {
        DoubleSupplier doubleSupplier = () -> 5;
        // System.out.println(doubleSupplier.getAsDouble());
        String[] atp = {"Rafael Nadal", "Novak Djokovic",
                "Stanislas Wawrinka",
                "David Ferrer", "Roger Federer",
                "Andy Murray", "Tomas Berdych",
                "Juan Martin Del Potro"};
        List<String> players = Arrays.asList(atp);

        // 以前的循环方式
      /*  for (String player : players) {
            System.out.print(player + "; ");
        }*/
        //lambda表达式遍历
        players.forEach((player) -> System.out.println(player + ""));
        //在Java8中使用双冒号操作符
        //  players.forEach(System.out::println);
    }

    /**
     * lambda生成匿名内部类
     */
    public static void anonymous(){
        //1.1使用lambda表达式
        new Thread(()->{
            System.out.println("黄世民");
        }).start();
        //1.2lambda表达式
        Runnable runnable=()-> System.out.println("黄世民");
        //直接调用(没开新线程)
        runnable.run();

    }
    static String[] players = {"Rafael Nadal", "Novak Djokovic",
            "Stanislas Wawrinka", "David Ferrer",
            "Roger Federer", "Andy Murray",
            "Tomas Berdych", "Juan Martin Del Potro",
            "Richard Gasquet", "John Isner"};
    /**
     * 使用lambda集合排序
     */
    public static void sort(){
        //1.2 使用 lambda expression 排序 players
        Comparator<String> stringComparator = (String s1, String s2) -> (s1.compareTo(s2));
        Arrays.sort(players,stringComparator);
        // 1.3 也可以采用如下形式:
        Arrays.sort(players, (String s1, String s2) -> (s1.compareTo(s2)));
        Arrays.asList(players).forEach(s -> {
            System.out.println(s+":");
        });

    }

    public static void main(String[] args) {
        //basicTest();
        //anonymous();
        sort();
    }
}
